package asapIs134CK.womi.client.profile;

import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.SimplePanel;

public class UserDisplay extends Composite{
	private static UserDisplay _instance = null;
	private SimplePanel panel;
	private HTMLPanel wait;
	private final RPCUserServiceAsync userService = GWT
	.create(RPCUserService.class);
	private UserDisplay(){
		panel = new SimplePanel();
		panel.setStyleName("UserDisplay");
		wait = new HTMLPanel(
				"<div><img id=\"loadingGif\" src=\"imgs/ajax-loader.gif\" alt=\"Loading...\" /></div>");

		this.initWidget(panel);
		refresh();
	}
	
	public static UserDisplay getInstance(){
		if(_instance == null){
			_instance = new UserDisplay();
		}
		return _instance;
	}
	
	public void authenticated(UserClient user){
		panel.clear();
		panel.add(new AuthenticatedUserDisplay(user, this));
	}

	public void requestSignIn() {
		panel.clear();
		panel.add(new SignInUserDisplay(this));
	}

	public void displayDefault() {
		panel.clear();
		panel.add(new DefaultUserDisplay(this));
	}
	
	public HTMLPanel getWait(){
		return this.wait;
	}

	public void refresh() {
		panel.clear();
		panel.add(wait);

		AsyncCallback<UserClient> callback = new AsyncCallback<UserClient>() {
			public void onFailure(Throwable caught) {
				displayDefault();
			}

			public void onSuccess(UserClient result) {
				if(result == null){
					displayDefault();
				}
				else {
					authenticated(result);
				}
			}
		};
		userService.getCurrentUser(callback);
	}
}
